<template>
  <section :class="status === -1 ? 'detailContent' : 'content'">
    <details-head v-if="status === -1"
                  :title="`已关闭详情`"
                  :multiple="true" />
    <el-form ref="ruleForm"
             class="form"
             label-width="100px"
             :model="form"
             label-position="right"
             size="small">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item v-if="createType === 1"
                        label="发货方名称:"
                        prop="customerName"
                        :rules="[{ required: true, message: `请输入发货方名称`, trigger: 'blur' }]">
            <div>
              <Tooltip v-if="iconName"
                       :content="content"
                       :placement="placement">
                <icon-svg class-name="iconClass mr5"
                          :icon-name="iconName" />
              </Tooltip>
              {{ form.customerName }}
            </div>
          </el-form-item>
          <el-form-item v-else
                        label="承运方名称:"
                        prop="carrierName"
                        :rules="[{ required: true, message: `请输入承运方名称`, trigger: 'blur' }]">
            <div>
              <Tooltip v-if="iconName"
                       :content="content"
                       :placement="placement">
                <icon-svg class-name="iconClass mr5"
                          :icon-name="iconName" />
              </Tooltip>
              {{ form.carrierName }}
            </div>
            <!-- <el-input v-else
                      v-model="form.carrierName"
                      disabled /> -->
          </el-form-item>
          <el-form-item label="对账单名称:"
                        prop="name"
                        :rules="[{required: true, message: `请输入对账单名称`, trigger: 'blur' }]">
            <div v-if="textFlag">{{ form.name }}</div>
            <el-input v-else
                      v-model="form.name"
                      maxlength="30" />
          </el-form-item>
          <el-form-item label="制单时间:"
                        prop="preparationTime"
                        :rules="[{ required: true }]">
            <div>{{ form.preparationTime }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="摘要:"
                        prop="desc">
            <div v-if="textFlag"
                 class="descSty">{{ form.desc || "--" }}</div>
            <el-input v-else
                      v-model="form.desc"
                      type="textarea"
                      :rows="5"
                      maxlength="200"
                      placeholder="请输入摘要"
                      show-word-limit />
          </el-form-item>
        </el-col>
        <el-col v-if="status != -1"
                :span="8"
                class="footer-item">
          <el-button type="primary"
                     plain
                     @click="back">返回</el-button>
          <el-button v-if="!textFlag"
                     type="primary"
                     :loading="loading"
                     @click="handleCreate">保存</el-button>
          <el-button v-if="billId && !textFlag"
                     type="primary"
                     :loading="loading"
                     @click="submit(0)">发送</el-button>
          <el-button v-if="status === 20"
                     type="primary"
                     :loading="loading"
                     @click="submit(1)">撤回</el-button>
          <el-button v-if="status === 10"
                     type="primary"
                     :loading="loading"
                     @click="submit(2)">同意</el-button>
          <el-button v-if="status === 10"
                     type="primary"
                     @click="handleRefuse">拒绝</el-button>
        </el-col>
        <el-col v-if="tipsVisible && (!billId || status === 0 || !status)"
                :span="8"
                class="tipsCont">
          <div class="tipsSty">对方已开启委托对账，发送后将自动审核</div>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-header">
      <div class="table-tips">
        <div v-if="[0,10,40,60].includes(status) || !status">
          <icon-svg class-name="iconClass mlr"
                    icon-name="tishi" />
          红色文字表示该运单未回单
        </div>
      </div>
      <div v-if="!textFlag">
        <el-button :disabled="!billId"
                   :loading="loading"
                   @click="batchDelete">批量删除</el-button>
        <el-button :disabled="!billId"
                   @click="handleVisable">选择新增运单</el-button>
      </div>
    </div>
    <div>
      <account-list v-if="status != -1"
                    ref="accountList"
                    :bill-id="billId"
                    :current-data="currentData"
                    :col-width="202"
                    :status="status"
                    :page="page"
                    :page-size="pageSize"
                    :selection-flag="!textFlag"
                    :operation-flag="!textFlag"
                    :desc-flag.sync="descFlag"
                    :total-data="totalData"
                    :total-loading.sync="totalLoading"
                    :create-type="createType"
                    total-flag
                    ship-orsend
                    @valid="valid"
                    @deleteHandel="deleteHandel" />
    </div>
    <div v-if="status != -1"
         class="footer-item mt12">
      <el-pagination :current-page="page"
                     :page-size="pageSize"
                     :total="total"
                     :page-sizes="[10, 50, 100, 500, 1000]"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </div>
    <add-account-list-dialog v-if="childVisible"
                             :child-visible.sync="childVisible"
                             :index-list="currentData"
                             :create-type="createType"
                             :customer-id="form.customerId"
                             :driver-id="form.driverId"
                             :carrier-id="form.carrierId"
                             @changeTableData="changeTableData" />
    <reject :id="billId"
            :label="'reason'"
            :api="api.refuse"
            :title="'拒绝原因'"
            id-name="billId"
            :is-close="false"
            :visible.sync="visible"
            @back="back" />
    <SimpleTab v-show="isTrack"
               title="跟踪信息">
      <Information :value="track" />
    </SimpleTab>
  </section>
</template>

<script>
import DetailsHead from "@/components/detailsHead/Header";
import AccountList from "./components/AccountList.vue";
import AddAccountListDialog from "./components/AddAccountListDialog.vue";
import Reject from "@/views/quote/transport/components/Reject.vue";
import SimpleTab from "@/components/basic/SimpleTab.vue";
import Information from "@/components/track/Information.vue";
import { finance, carrier, customer, track } from "@/api/index";
import { pageTotal, billCache } from "./components/financeMap";
import Tooltip from "@components/basic/Tooltip.vue";
import { mapState } from "vuex";
import _ from 'lodash'
export default {
  name: "CreateAccountStatement",
  components: {
    AccountList,
    AddAccountListDialog,
    Reject,
    SimpleTab,
    Information,
    Tooltip,
    DetailsHead
  },
  data () {
    return {
      loading: false,
      api: finance,
      childVisible: false,
      descFlag: false, //审核对账时 是否填写问题描述
      page: 1,
      pageSize: 10,
      total: 0,
      tableData: [], //总数据源
      currentData: [], //当前页数据
      totalData: [ //合计数据源
        { contractNo: '本页合计' },
        { contractNo: "总合计" }
      ],
      totalLoading: false,
      form: {
        name: null,
        desc: null,
        preparationTime: "自动生成制单时间",
        status: null
      },
      pageTotal, //本页小计
      billCache, //全部合计
      tipsVisible: false, //是否显示委托付款提示语
      track: [], // 跟踪信息
      isTrack: false, // 跟踪信息标题显示
      visible: false
    };
  },
  computed: {
    ...mapState({
      linkParams: (state) => state.link.linkParams
    }),
    createType () {
      // 创建对账单类型 1应收 2应付
      const { name } = this.$route
      return ['customerAccountStatement', 'customerDraftAccountStatement', 'customerAccountStatementWindow'].includes(name) ? 1 : 2
    },
    status () {
      return this.form?.status
    },
    isDraft () {
      const { name } = this.$route
      return ['customerDraftAccountStatement', 'carrierDraftAccountStatement'].includes(name) || (this.form.status === 0)
    },
    textFlag () {
      // 详情页形态显示 状态：50、60 对账单/待审核/审核对账/已关闭
      return this.status && [50, 60, 20, 10, -1].includes(this.status);
    },
    billId () {
      return this.$route.query?.id || this.$route.query?.billId || this.linkParams.billId
    },
    params () {
      const paramsObj = {
        billId: this.billId,
        page: this.page || 1,
        size: this.pageSize || 10
      };
      console.log("-=======", this.isDraft)
      if (!this.isDraft) {
        paramsObj.sort = [{ asc: false, name: "fromTime" }]
      }
      // if ([40, '40'].includes(this.status)) { paramsObj.sort = [{ asc: false, name: "problemDesc" }]; }
      return paramsObj;
    },
    placement () {
      return 'top'
    },
    content () {
      const { customerType, carrierType, carrierExtraType } = this.form
      if (this.createType === 1) {
        switch (customerType) {
          case 0:
            return '线下';
          case 1:
            return '线上';
          default:
            return '';
        }
      } else {
        if (carrierType === 0) {
          return '线下';
        }
        if (carrierType === 1 && carrierExtraType == 0) {
          return '线上';
        }
      }
      return '';
    },
    iconName () {
      const { customerType, carrierType, carrierExtraType } = this.form
      if (this.createType === 1) {
        switch (customerType) {
          case 0:
            return 'xianxia';
          case 1:
            return 'xianshang';
          default:
            return '';
        }
      } else {
        if (carrierType === 0) {
          return 'xianxia';
        }
        if (carrierType === 1 && carrierExtraType == 0) {
          return 'xianshang';
        }
      }
      return '';
    }
  },
  created () {
    const { batchEntry } = this.linkParams
    if (this.billId) {
      this.getBillDetail(this.params);
    } else {
      this.total = batchEntry.length;
      this.tableData = batchEntry;
      this.currentData = JSON.parse(JSON.stringify(this.tableData)).splice(0, this.pageSize);
      this.form.carrierId = this.tableData[0].carrierId;
      this.form.customerId = this.tableData[0].customerId;
      if (this.createType === 1) {
        this.form.customerName = this.tableData[0].showCustomerName || this.tableData[0].customerName;
        this.form.customerType = this.tableData[0].showCustomerType;
        this.getCarrierById(this.tableData[0].carrierId)
      } else {
        /* 自营司机 */
        this.form.driverId = this.tableData[0].driverId || null;
        this.form.carrierName = this.tableData[0].carrierName;
        this.getCustomerById(this.tableData[0].customerId)
      }
    }
    this.trackInformation();
  },
  beforeDestroy () {
    for (let key in pageTotal) {
      pageTotal[key] = 0;
    }
    for (let key in billCache) {
      billCache[key] = 0;
    }
  },
  methods: {
    handleSizeChange (value) {
      if (this.billId) {
        this.page = 1;
        this.pageSize = value;
        this.getBillDetail({ ...this.params, size: value });
      } else {
        let arr = JSON.parse(JSON.stringify(this.tableData)).splice(0, value);
        this.currentData = [...arr];
        this.page = 1;
        this.pageSize = value;
      }
    },
    handleCurrentChange (value) {
      if (this.billId) {
        this.page = value;
        this.getBillDetail({ ...this.params, page: this.page, billId: this.billId });
      } else {
        let arr = JSON.parse(JSON.stringify(this.tableData)).splice(
          (value - 1) * this.pageSize,
          value * this.pageSize
        );
        this.currentData = [...arr];
        this.page = value;
        this.total = this.tableData.length;
      }
    },
    // 新增运单弹窗显示
    handleVisable () {
      if (this.billId) {
        this.childVisible = true;
      } else {
        this.valid();
      }
    },
    // 添加运单
    changeTableData (data) {
      if (data.length > 0) {
        if (this.billId) {
          let waybillIds = data.map((item) => { return item.waybillId; });
          this.addRes({ billId: this.billId, waybillIds });
        } else {
          this.tableData.push(...data);
          this.handleCurrentChange(this.page);
        }
      }
    },
    // 承运方详情
    async getCarrierById (carrierId) {
      let { data } = await carrier.getCarrierById(carrierId);
      this.tipsVisible = data && data?.autoBalance
    },
    // 发货方详情
    async getCustomerById (customerId) {
      let { data } = await customer.getCustomerById(
        customerId
      );
      this.tipsVisible = data && data?.autoBalance
    },
    async addRes (params) {
      await finance.addRes(params);
      this.$message.success("操作成功！");
      if (this.status == 40) {
        this.form.status = 0
      }
      this.handleCurrentChange(this.page);
    },
    deleteHandel (index, waybillId) {     // 删除
      if (this.billId) {
        this.deleteRes({ billId: this.billId, waybillId });
      } else {
        this.tableData.splice(index, 1);
        this.handleCurrentChange(this.page);
      }
    },
    async deleteRes (params) {
      await finance.deleteRes(params);
      this.$message.success("操作成功！");
      if (this.status == 40) {
        this.form.status = 0
      }
      if (this.pageSize === 10 && this.total > 10 && this.total.toString()[1] === '1') {
        this.page = this.page - 1
      }
      if ([50, 100, 500, 1000].includes(this.pageSize)) {
        this.page = 1
      }
      this.handleCurrentChange(this.page);
    },
    // 验证对账单名称
    valid () {
      this.$refs.ruleForm.validateField("name", (valid) => {
        if (valid) {
          console.log("valid", valid);
        }
      });
    },
    batchDelete: _.debounce(function () {
      if (!this.billId) { return this.valid(); }
      this.loading = true;
      if (
        this.$refs.accountList.selectData &&
        this.$refs.accountList.selectData.length > 0
      ) {
        if (this.billId) {
          let waybillIds = this.$refs.accountList.selectData.map((item) => {
            return item.waybillId;
          });
          this.batchDeleteRes({ billId: this.billId, waybillIds });
        } else {
          let arr = [...this.tableData];
          this.$refs.accountList.selectData.map((item) => {
            arr.map((ele, index) => {
              if (ele.waybillId === item.waybillId) { arr.splice(index, 1); }
            });
          });
          this.tableData = arr;
          this.handleCurrentChange(this.page);
        }
      } else {
        this.loading = false;
        this.$message.error("至少选择一个运单");
      }
    }, 600),
    async batchDeleteRes (params) {
      let { code } = await finance.batchDeleteRes(params)
        .catch(() => {
          this.loading = false;
        });
      if (code === 0) {
        if (this.status == 40) {
          this.form.status = 0
        }
        this.loading = false;
        this.$message.success("操作成功！");
        let uTotal = this.total - this.$refs.accountList.selectData.length
        if (this.pageSize === 10 && uTotal > 9 && uTotal.toString()[1] === '0') { this.page = this.page - 1 }
        if ([50, 100, 500, 1000].includes(this.pageSize)) { this.page = 1 }
        this.handleCurrentChange(this.page);
      }
    },
    async handleCreate () {
      this.$refs.ruleForm.validateField("name", (nameValid) => {
        console.log("======nameValid", nameValid)
      });
      if (!this.form.name) return false;
      this.loading = true;
      if (this.billId) {
        this.updateBill({ billId: this.billId, ...this.form }, false);
      } else {
        if (this.tableData.length < 1) {
          this.loading = false;
          return this.$message.error("运单不能为空！请添加运单");
        }
        let waybillIds = this.tableData.map((item) => { return item.waybillId; });
        let { data } = this.createType === 1
          ? await finance.createReceivable({ ...this.form, waybillIds }).catch(() => { this.loading = false; })
          : await finance.createPayable({ ...this.form, waybillIds }).catch(() => { this.loading = false; });
        this.loading = false;
        this.billId = data;
        this.getBillDetail({ ...this.params, billId: data });
        this.$message.success("已生成对账单！");
      }
    },
    async getBillDetail (params) {
      this.tipsVisible = false
      this.totalLoading = true;
      let { data } = await finance.getBillDetail(params)
        .catch(err => {
          this.totalLoading = false;
        });
      this.form = {
        customerName: data.showCustomerName || data.customerName || data?.billSpecs?.records[0]?.showCustomerName || data?.billSpecs?.records[0]?.customerName,
        customerId: data?.customerId || data?.billSpecs?.records[0]?.customerId,
        carrierName: data.carrierName || data?.billSpecs?.records[0]?.carrierName,
        carrierId: data?.carrierId || data?.billSpecs?.records[0]?.carrierId,
        carrierType: data?.carrierType,
        customerType: data?.customerType,
        carrierExtraType: data?.carrierExtraType,
        driverId: data?.driverId || data?.billSpecs?.records[0]?.driverId,
        name: data.name,
        desc: data.desc,
        status: data.status,
        preparationTime: data.createAt
      };
      if (this.createType === 1) {
        if ((this.status === 0 || !this.status) && this.form.carrierId) {
          this.getCarrierById(this.form.carrierId)
        }
      } else {
        if ((this.status === 0 || !this.status) && this.form.customerId) {
          this.getCustomerById(this.form.customerId)
        }
      }
      this.tableData = data?.billSpecs?.records;
      this.currentData = data?.billSpecs?.records;
      let pageTotal = data.pageTotal;
      let billCache = data.billCache;
      for (let key in pageTotal) {
        let name = key.substring(5, key.length);
        let toLower = name[0].toLowerCase() + name.substr(1);
        pageTotal[toLower] = pageTotal[key];
      }
      for (let key in billCache) {
        let name = key.substring(5, key.length);
        let toLower = name[0].toLowerCase() + name.substr(1);
        billCache[toLower] = billCache[key];
      }
      this.totalData = this.addTableFooter(pageTotal, billCache);
      this.total = data?.billSpecs?.total || 0;
    },
    // 合计表数据源
    addTableFooter (page, total) {
      this.totalLoading = false;
      return [{
        contractNo: '本页合计',
        ...pageTotal,
        ...page
      }, {
        contractNo: "总合计",
        ...billCache,
        ...total
      }];
    },
    async updateBill (params, sendFlag) {   // 修改对账单
      let { code } = await finance.updateBill(params)
        .catch(() => {
          this.loading = false;
        });
      if (code === 0) {
        if (sendFlag) {
          this.sendOut();
        } else {
          this.loading = false;
          this.$message.success("操作成功！");
        }
      }
    },
    async sendOut () {     // 发送
      let { code } = await finance.sendOut({ billId: this.billId })
        .catch(() => {
          this.loading = false;
        });
      if (code === 0) {
        this.loading = false;
        this.$message.success("发送对账单成功！");
        this.back();
      }
    },
    async recallBill () {  // 撤回
      await finance.recallBill({ billId: this.billId });
      this.$message.success("撤回成功！");
      this.back();
    },
    async agree () {     // 同意
      await finance.agree({ billId: this.billId });
      this.$message.success("操作成功！");
      this.back();
    },
    handleRefuse () {   // 拒绝
      this.visible = true;
    },
    submit: _.debounce(function (val) {    // 触发事件
      if (val === 0) {
        if (!this.billId || !this.form.name) { return this.valid(); }
        if (this.tableData.length < 1) { return this.$message.error("未有运单,请选择增加运单!"); }
      }
      let agreeTips = "确定同意？";
      if (val === 2) {
        let flag = false;
        this.currentData.map((item) => {
          if (item.problemDesc) { return (flag = true); }
        });
        if (flag || this.descFlag) { agreeTips = "列表里已填写了问题描述，同意后问题描述不生效"; }
      }
      let tips = ["是否确认发送对账单", "是否确认撤回对账单", agreeTips];
      this.$confirm(`${tips[val]}`, "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (val === 0) {
          this.updateBill({ billId: this.billId, ...this.form }, true);
        } else if (val === 1) {
          this.recallBill();
        } else {
          this.agree();
        }
      });
    }, 600),
    back () {   // 返回
      this.$router.back();
    },
    // 跟踪信息
    async trackInformation () {
      let type = 'bill'
      if (this.billId) {
        let { code, data } = await track.information(this.billId, type);
        if (code === 0 && data.length) {
          data.map(item => {
            if (item.message.indexOf('，') != -1 && item.message.lastIndexOf('】')) {
              item.timestamp = item.message.slice(0, item.message.indexOf('，'))
              item.date = item.message.slice(item.message.indexOf('，') + 1, item.message.lastIndexOf('】') + 1)
              item.content = item.message.slice(item.message.lastIndexOf('】') + 1)
            }
          })
          this.track = data
          this.isTrack = true
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.detailContent {
  width: 1200px;
  height: calc(100vh);
  overflow-x: hidden;
  overflow-y: scroll;
  background: var(--prev-bg-white);
  margin: 0 auto;
}
.content {
  background: var(--prev-bg-white);
  padding: 20px;
  position: relative;
  height: 88vh;
  overflow-y: auto;
}
.form {
  padding: 20px;
}
.pl40 {
  padding-left: 40px;
}
.fontSty {
  color: var(--prev-color-text-darkgrey);
}
.table-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.table-tips {
  color: var(--prev-border-color-yellow);
  line-height: 34px;
}
.mlr {
  margin-left: 25px;
  margin-right: 8px;
}
.footer-item {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.mt12 {
  margin-top: 12px;
}
.tipsCont {
  display: flex;
  justify-content: flex-end;
}
.tipsSty {
  display: flex;
  justify-content: center;
  background: rgba(255, 255, 255, 0.39);
  box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.16);
  opacity: 1;
  width: 280px;
  height: 48px;
  font-size: 14px;
  font-weight: 400;
  line-height: 48px;
  border-radius: 4px;
  color: var(--prev-color-text-ashes);
  margin-top: 20px;
}
.descSty {
  word-break: break-all;
}
.iconClass {
  width: 14px;
  height: 14px;
}
</style>
